package com.liaoban.app.ui.mine;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.TextView;

import com.liaoban.app.R;
import com.liaoban.app.api.type.event.AutoInstallEvent;
import com.liaoban.app.api.type.event.DownloadEvent;
import com.liaoban.app.api.type.event.LogoutEvent;
import com.liaoban.app.api.type.request.SendGiftReq;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ConfigKey;
import com.liaoban.app.helper.ConfigHelper;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.MainActivity;
import com.liaoban.app.ui.base.BaseToolbarActivity;
import com.liaoban.app.ui.message.MyAVChatActivity;
import com.liaoban.app.update.UpdateHelper;
import com.liaoban.app.util.CleanMessageUtil;
import com.liaoban.app.util.CommonUtils;
import com.liaoban.app.util.RxUtils;
import com.liaoban.app.widget.MyAlertDialog;
import com.liaoban.app.widget.SendGiftDialog;
import com.netease.nim.avchatkit.constant.CallStateEnum;
import com.netease.nim.uikit.support.permission.MPermission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ybc on 2018/7/13 0013.
 * 设置
 */
public class SetActivity extends BaseToolbarActivity {
    private static final int INSTALL_APK_REQUESTCODE = 101;
    private static final int GET_UNKNOWN_APP_SOURCES = 102;
    @BindView(R.id.tv_cache)
    TextView tvCache;
    @BindView(R.id.tv_version)
    TextView tvVersion;

    private ProgressDialog mDownloadPd;
    private File mApkFile;

    @Override
    protected String getNewTitle() {
        return "设置";
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_set;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setNeedOnBus(true);
        initCache();
        tvVersion.setText("V" + CommonUtils.getVersionName(this));
    }

    //计算当前缓存的大小
    private void initCache() {
        try {
            tvCache.setText(CleanMessageUtil.getTotalCacheSize(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.layout_cache)
    public void cache() {
        CleanMessageUtil.clearAllCache(this);
        ToastHelper.show(this, getString(R.string.suc_clean_cash));
        initCache();
    }

    @OnClick(R.id.layout_feed_back)
    public void feedBack() {
        startActivity(new Intent(this, FeedBackActivity.class));
    }

    @OnClick(R.id.tv_logout)
    public void logout() {
        new MyAlertDialog(this).builder().setMsg(getString(R.string.confirm_logout)).
                setPositiveButton("", view -> {
                    showRunningDialog();
                    startTask(CommonBiz.getInstance().logout(), baseResponseBaseResponse -> {
                        /*CommonUtils.logout(this);
                        EventBus.getDefault().post(new LogoutEvent());
                        finish();*/
                    });
                })
                .setNegativeButton("", null).show();
    }

    @OnClick(R.id.layout_version)
    public void version() {
        UpdateHelper.getInstance().doUpdateCheckRequest(this, true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDownloadEvent(DownloadEvent downloadEvent) {
        Intent intent = new Intent(this, SetActivity.class);
//        Log.e("yubch", "SetActivity is Top:" + CommonUtils.isTop(this, intent));
        if (CommonUtils.isTop(this, intent)) {
            showDownloadPd(downloadEvent.mProgress);
        }
    }

    /**
     * 下载进度条
     *
     * @param progress
     */
    private void showDownloadPd(int progress) {
        if (mDownloadPd == null) {
            mDownloadPd = new ProgressDialog(this);
            mDownloadPd.setTitle("正在下载...");
            mDownloadPd.setCanceledOnTouchOutside(true);
            mDownloadPd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mDownloadPd.setMax(100);
        }
        tvCache.post(() -> mDownloadPd.setProgress(progress));
        if (progress < 100) {
            mDownloadPd.show();
        } else {
            mDownloadPd.dismiss();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAutoInstallEvent(AutoInstallEvent autoInstallEvent) {
        Intent intent = new Intent(this, SetActivity.class);
        if (CommonUtils.isTop(this, intent)) {
            mApkFile = autoInstallEvent.mApkFile;
            autoInstallEvent();
        }
    }

    private void autoInstallEvent() {
        if (Build.VERSION.SDK_INT >= 26) { //8.0
            //来判断应用是否有权限安装apk
            boolean installAllowed = getPackageManager().canRequestPackageInstalls();
            //有权限
            if (installAllowed) {
                //安装apk
                autoInstall(mApkFile);
            } else {
                //无权限 申请权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_APK_REQUESTCODE);
            }
        } else {
            autoInstall(mApkFile);
        }
    }

    private void autoInstall(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
            data = FileProvider.getUriForFile(this, "com.liaoban.app.fileprovider", apkFile);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(apkFile);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        startActivity(intent);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        switch (requestCode) {
            case INSTALL_APK_REQUESTCODE:
                //有注册权限且用户允许安装
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    autoInstall(mApkFile);
                } else {
                    //将用户引导至安装未知应用界面。
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
                    ToastHelper.show(this, "设置中，请打开允许安装未知应用");
                }
                break;
            case GET_UNKNOWN_APP_SOURCES:
                autoInstallEvent();
                break;
            default:
                break;
        }
    }
}
